package org.base.admin.modules.sys.controller;

import java.util.List;

import org.base.admin.modules.base.AbstractController;
import org.base.admin.modules.sys.service.SysMenuService;
import org.base.admin.utils.web.WebSecurityUtils;
import org.base.common.R;
import org.base.common.ResponseCode;
import org.base.dao.common.Page;
import org.base.dao.modules.sys.model.SysMenuDO;
import org.base.dao.modules.sys.model.SysUserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/menu")
public class SysMenuController extends AbstractController {
	
	@Autowired
	private SysMenuService sysMenuService;
	
	
	@PostMapping("/list")
	public R list(@RequestBody Page<SysMenuDO> page) {
		return R.result(sysMenuService.findPage(page));
	}
	
	@GetMapping("/get/{id}")
	public R info(@PathVariable("id") Long id) {
		return R.result(sysMenuService.findById(id));
	}
	
	@GetMapping("/user")
	public R userMenus() {
		SysUserDO user = WebSecurityUtils.getUser();
		return R.result(
				user.isAdmin()?
					sysMenuService.findAdminMenus():
					sysMenuService.findUserMenus(user.getId())
				);
	}
	
	@PostMapping("/save")
	@PreAuthorize("hasAuthority('create')")
	public R save(@RequestBody SysMenuDO entity) {
		return sysMenuService.save(entity)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
		
	}
	
	@PutMapping("/update")
	@PreAuthorize("hasAuthority('write')")
	public R update(@RequestBody SysMenuDO entity) {

		return sysMenuService.updateById(entity)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
	}
	
	@DeleteMapping("/remove/{id}")
	@PreAuthorize("hasAuthority('delete')")
	public R remove(@PathVariable("id") Long id) {
		return sysMenuService.removeById(id)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
	}
	
	@DeleteMapping("/remove")
	@PreAuthorize("hasAuthority('delete')")
	public R removeList(@RequestBody List<Long> ids) {
		return sysMenuService.removeByIds(ids)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
	}
	
	@Override
	public String authoritiesPrefix() {
		return null;
	}

}
